from datetime import timedelta

from rest_framework import serializers
from task_manage_sys.serializers import DynamicFieldModelSerializer
from user.models import User, Clazz, PersonGroup


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

        fields = ['id', 'username', 'email', 'password', 'first_name', 'last_name', 'is_active', 'is_staff', 'clazz']

        extra_kwargs = {
            'password': {'write_only': True}
        }

    def create(self, validated_data):
        validated_data["is_active"] = True
        return User.objects.create_user(**validated_data)


class ClazzSerializer(DynamicFieldModelSerializer):
    graduate_time = serializers.SerializerMethodField(method_name="get_graduate_time")

    def get_graduate_time(self, model):
        return model.start_time + timedelta(days=model.duration * 30)

    class Meta:
        model = Clazz
        fields = '__all__'


class GroupSerializer(DynamicFieldModelSerializer):
    name = serializers.ReadOnlyField(source="group.name")

    num = serializers.IntegerField(read_only=True)

    class Meta:
        model = PersonGroup
        fields = '__all__'
